define(function(require, exports, module) {
    'use strict';
    
    require('lib/fullcalendar/fullcalendar');
    if(SESSION.user.language === 'zh-cn'){
        require('lib/fullcalendar/lang/zh-cn.rkhd');
    }
    require('../plus/fullCalendarPlus');
    require('../controllers/calEventFilterCtrl');
    require('../controllers/calEventTypeSelCtrl');
    require('../controllers/calOwnerSelCtrl');
    require('./platform_schedule-index-eventEditor');
    
    var rk_userService = require('userService');
    //var scheduleService = require('scheduleService');
    // require('globaljs');
    var rk = require('rk');

    var scheduleUtil = require('oa/js/schedule/asset/utils/scheduleUtil');

    var currentPageUserId = SESSION.user.id;

    var calendarPage = {};

    //calendar
    (function() {
        //start!
        function init(opt){
            scheduleUtil.retriveDisplaySetting();
            initScheduleHtml();        
            initCalendar(opt);
            initCalendarHeader();
            initCreateButton();
            //initData();
            //initGuider();
        };
        //对外
        calendarPage.init = init;

        var MONDAY = 1,
            TUESDAY = 2,
            WEDNESDAY = 3,
            THURSDAY = 4,
            FRIDAY = 5,
            SATURDAY = 6,
            SUNDAY = 7;
        var g_calendarId = 'calendar';
        var g_editorTipId = 'calendarEditor';
        var g_editorTipInstance,
            g_calendarInstance;
        var g_popedTipIds = [];

        var headImageWidth = 12;
        var headImageHeight = 12;

        function initScheduleHtml(){
            var header = $('.header_content:first');
            header.addClass('schedule_header_content');
        }
        function initData() {
            scheduleUtil.loadEvents();
            scheduleUtil.fireEvent('dataInited');
            return;
            scheduleUtil.showBusy();
            var url = '/json/crm_schedule/index.action';
            var view = $('#calendar').fullCalendar('getView');
            var startDate = view.start.format('YYYY-MM-DD');
            var endDate = view.end.format('YYYY-MM-DD');
            var userId = scheduleUtil.getDisplaySetting('userId');
            var cookie_userId = scheduleUtil.getDisplaySettingByCookie('userId');
            if(typeof cookie_userId != 'undefined'){
                userId = cookie_userId;
            }
            var showTask = scheduleUtil.getDisplaySetting('showTask');
            var scheduleTypes = scheduleUtil.getDisplaySetting('scheduleTypes');
            var onlyShowUnfinishedTasks = scheduleUtil.getDisplaySetting('onlyShowUnfinishedTasks');
            var param = 'userId=' + userId +
                '&startDate=' + startDate +
                '&endDate=' + endDate +
                '&showTask=' + (showTask ? '1' : '0') +
                '&scheduleTypes=' + scheduleTypes +
                '&isFinish=' + (onlyShowUnfinishedTasks ? '0' : '1') +
                '&_r=' + Math.random();
            $.ajax({
                url: url,
                data: param,
                dataType: 'json'
            }).success(function(data) {
                    rk_userService.loadUser(data);
                    rk_userService.loadRecentUserList(data);
                    scheduleUtil.loadUnAcceptedNum(data);
                    scheduleUtil.loadEvents(data);
                    scheduleUtil.getInitColorList(data);
                    scheduleUtil.fireEvent('dataInited');
                })
                .error(function() {})
                .done(function() {
                    $('#calendar').fullCalendarPlus('resetMyHeight');
                    scheduleUtil.hideBusy();
                });
        };
        function updateDayTitle_by_asking(){
            var h2 = $('.fc-header-title').find('h2');
            var title = h2.html();
            //英文星期取不到，日历中有星期，因此暂时先不显示
            if(SESSION.user.language === 'zh-cn'){
                var splitor = "星期";
                var arr = title.split(splitor);
                title = arr[0] + '&nbsp;' + splitor + arr[1];
            }else{
                title = moment(title).format('YYYY-MM-DD');
            }
            h2.html(title);
        }
        function updateWeekTitle_by_asking(){
                var h2 = $('.fc-header-title').find('h2');
                var title = h2.html();
                var splitor = ' - ';
                var arr = title.split(splitor);
                title = arr[0] + rk.i18n('SCHEDULE_DAY_HIDE') + splitor + arr[1];
                h2.html(title);
        }
        
        var g_selectedDate;

        function initCalendar(opt) {
            if(typeof opt == 'undefined') opt = {};
            //init calendar
            g_calendarInstance = $('#' + g_calendarId).fullCalendarPlus().fullCalendar({
                header: {
                    left: '',//'agendaDay agendaWeek month',
                    center: 'prev title next ',
                    right: ''
                },
                scrollTime:'08:00:00',
                //contentHeight: 1600,
                defaultView: ( opt.view ? opt.view : 'agendaWeek'),
                lang: 'zh-cn',
                defaultDate: $.fullCalendar.moment(), //today, or try a date string like '2014-06-12',
                editable: true,
                weekends: true,
                weekMode: 'variable',
                firstDay: MONDAY,
                selectable: true,
                selectHelper: true,
                //allDaySlot: false,
                handleWindowResize: true,
                axisFormat: 'H:mm', //'h(:mm)a',
                timeFormat: 'H:mm',
                columnFormat: {
                    month: 'dddd', // Mon
                    week: 'D' + rk.i18n('SCHEDULE_DAY') + 'dddd', // Mon 9/7
                    day: 'dddd' // Monday
                },
                titleFormat: {
                    month: 'LL',
                    week: "ll",
                    day: "LLL"
                },
                slotEventOverlap: false,
                eventRender: function(event, element, view) {
                    element.find('.fc-event-title').html(event.title);
                    element.attr('event-id', event.id);
                },
                eventAfterRender: function(event, element, view) {},
                viewRender: function(view, element) {
                    hideTips();
                    hideTimeline();
                    g_selectedDate = null;
                    if (!g_calendarInstance) return;
                    window.clearTimeout(window.btn_now_timer);
                    window.btn_now_timer = window.setTimeout(function() {
                        updateBtnNow(view.name);
                    }, 10);
                    _selectedTimeScope = null;
                    scheduleUtil.loadEvents();

                    //与右侧同步
                    var viewName = view.name;
                    var alias = scheduleUtil.getAliasName(viewName);
                    /*var calendar = $('#calendar');
                    if(calendar.data('do-no-refresh-panel')){
                        calendar.removeData('do-no-refresh-panel');
                    }else{*/
                        $('#oa_panel').schedulePanelCtrl('goto', alias, view.intervalStart.format());
                    //}
                },
                eventMouseover: function(event, jsEvent, view){
                    var target = $(jsEvent.target);
                    var ediv = target.is('[class~="fc-event"]') ? target : target.parents('div.fc-event');
                    var eventId = $(ediv).attr('event-id');
                    if(ediv.attr('tip-inited'))return;
                    ediv.eventViewerWindow({
                        event: event
                    });
                    ediv.attr('tip-inited','true');
                },
                eventClick: function(event, jsEvent, view) {
                    var target = $(jsEvent.target);
                    var eventId = $(target).attr('event-id');

                    // target.eventViewerWindow({
                    //             event: event
                    //         });
                    // return;
                    // // popupViewerTip(jsEvent, view, $.extend({
                    // //     act: 'edit',
                    // //     id: eventId
                    // // }, event));
                },
                dayClick: function(date, jsEvent, view) {
                    var viewName = view.name;
                    if(typeof scheduleUtil.dbl_click_marker == 'undefined')scheduleUtil.dbl_click_marker = false;
                    if(typeof scheduleUtil.dbl_click_timer == 'undefined')scheduleUtil.dbl_click_timer = null;
                    var isIE8 = ($.browser.msie && $.browser.version < 9);
                    var dbclick_delay = isIE8 ? 1200:200;

                    var currentDate = moment(date);
                    if(g_selectedDate && currentDate.isSame(g_selectedDate, 'day')){//单击已选中的日期也弹出
                        onDblClick();
                        g_selectedDate = null;
                    }else{
                        g_selectedDate = date;
                    }                

                    function onDblClick(){
                            var start = moment(date);
                            var end = moment(date);
                            hideTips();
                            if (viewName == 'month') {
                                popupEditorTip(jsEvent, view, {
                                    start: start,
                                    end: end
                                });
                                showGhostEvent(viewName, {
                                    start: moment(start),
                                    end: moment(end)
                                });
                            }
                    }
                    var target = $(jsEvent.target);
                    if(isIE8)
                    if(target && !target.attr('dbl-inited')){
                        target.dblclick(function(){
                            onDblClick();
                        });
                        target.attr('dbl-inited', 'true');
                    }
                    if(!isIE8)
                    if (scheduleUtil.dbl_click_marker == true) {
                        window.clearTimeout(scheduleUtil.dbl_click_timer); 
                        { //dblclick here
                            if(!isIE8) onDblClick();
                        }
                        scheduleUtil.dbl_click_marker = false;
                    } else {
                        scheduleUtil.dbl_click_marker = true;
                        window.clearTimeout(scheduleUtil.dbl_click_timer);
                        scheduleUtil.dbl_click_timer = window.setTimeout(function() {
                            { //single click here


                            }
                            scheduleUtil.dbl_click_marker = false;
                        }, dbclick_delay);
                    }
                },
                windowResize: function(view) {
                    var elem = this.element;
                    $(elem).fullCalendarPlus('showTimeline');
                },
                eventResizeStart: function() {},
                eventDragStart: function() {},
                viewDisplay: function() {},
                select: function(start, end, jsEvent, view) {
                    //fixbug: for event qtip viewer, qtip can not close when clicking on fullcalendar
                    try{
                        $('.qtip').qtip('destroy');
                    }catch(e){
                        console.log(e);
                    }

                    var viewName = view.name;
                    if (viewName != 'month') {
                        hideTips();
                        if (end.diff(start, 'minutes') > 30) {
                            if ($(jsEvent.target).hasClass('fc-cell-overlay')) {
                                //is clicked on the allDay area
                                window.allday_click_data = {};
                                window.allday_click_data.jsEvent = jsEvent;
                                window.allday_click_data.view = view;
                                window.allday_click_data.startend = {
                                    start: start,
                                    end: moment(start)//the orignal end will +1day, so don't use.
                                };
                            } else {
                                //is mouse select
                                popupEditorTip(jsEvent, view, {
                                    start: start,
                                    end: end,
                                    isAllDay: false
                                });
                            }
                        } else {
                            if (_selectedTimeScope && _selectedTimeScope.start.isSame(start) && _selectedTimeScope.end.isSame(end)) {
                                var opt = {
                                    start: start,
                                    end: end,
                                    isAllDay: false
                                };
                                popupEditorTip(jsEvent, view, opt);
                            }
                            _selectedTimeScope = {};
                            _selectedTimeScope.start = moment(start);
                            _selectedTimeScope.end = moment(end);
                        }
                    } else {
                        end = moment(end);
                        end.subtract(1, 'days');
                        var diffdays = end.diff(start, 'days');
                        if(diffdays > 0)
                        popupEditorTip(jsEvent, view, {
                            start: start.format('YYYY-MM-DD'),
                            end: end.format('YYYY-MM-DD'),
                            isAllDay: true
                        });                
                    }
                }
            });

            $('#calendar').on('dblclick', '.fc-cell-overlay', function() {
                if (!window.allday_click_data) return;
                popupEditorTip(
                    window.allday_click_data.jsEvent,
                    window.allday_click_data.view,
                    window.allday_click_data.startend
                );
            });

            /* GHOST EVENT*/
            function getNewEventTimeMom(start) {
                var end = moment(start);
                var start = moment(start);
                var now = moment();
                var hour = now.get('hours');
                var minate = now.get('minutes');
                if (now.isSame(start, 'day')) {
                    if (minate > 30) {
                        minate = 0;
                        hour = hour + 1;
                        if (hour > 23) hour = 23;
                    } else {
                        minate = 30;
                    }
                } else if (now.isBefore(start, 'day')) {
                    minate = 0;
                    hour = 8;
                } else if (now.isAfter(start, 'day')) {
                    minate = 0;
                    hour = 19;
                }
                var newtime = moment(start);
                newtime.hours(hour);
                newtime.minutes(minate);
                return newtime;
            }

            function _showGhostEvent(viewName, info) {
                removeGhostEvent(true);
                if (viewName != 'month') return;
                var newstart = getNewEventTimeMom(info.start);
                var newend = info.end;

                $('#calendar').fullCalendar('renderEvent', {
                    id: '_ghost',
                    title: 'SCHEDULE_ADD_EVENT',
                    className: 'rk-ghost-event',
                    allDay: true,
                    start: moment(newstart),
                    end: moment(newend),
                    backgroundColor: '#B3CED2',
                    borderColor: '#B3CED2',
                    textColor: '#fff'
                });
            };

            function showGhostEvent(viewName, info) {
                return;
                window.clearTimeout(window.show_ghost_timer);
                window.show_ghost_timer = window.setTimeout(function() {
                    _showGhostEvent(viewName, info);
                }, 80);
            }

            function removeGhostEvent(noDelay) {
                return;
                window.clearTimeout(window.remove_ghost_timer);
                if ($('#calendar').find('.fc-content').find('[event-id="_ghost"]').size() == 0) return;
                if (typeof noDelay != 'undefined') {
                    $('#calendar').fullCalendar('removeEvents', '_ghost');
                    return;
                }
                window.remove_ghost_timer = window.setTimeout(function() {
                    $('#calendar').fullCalendar('removeEvents', '_ghost');
                }, 80);
            };
            if (!scheduleUtil) scheduleUtil = {};
            scheduleUtil.removeGhostEvent = removeGhostEvent;

            /* SELECT */
            var _selectedTimeScope = null;
            //must hide tips when mouse down on day, week view
            $('#calendar').on('mousedown', '.fc-agenda-slots', function() {
                hideTips();
            });

            //mouseover day hightlight
            var currentHightlightDay;
            var highlightdayClass = 'fc-cell-mouseoverlay';
            $('#calendar').on('mouseover', '.fc-day', function() {
                if ($(currentHightlightDay).size() > 0) $(currentHightlightDay).removeClass(highlightdayClass);
                $(this).addClass(highlightdayClass);
                currentHightlightDay = $(this);
            });
            $('#calendar').on('mousemove', '.fc-event, fc-event-inner, fc-event-title', function() {
                var p = $(this).parents('.fc-day');
                if (p.size() > 0) {
                    p.addClass(highlightdayClass);
                }
            });
            //mouseover event highlight
            var hoveringEventObj;
            $('#calendar').on('mousemove', '.fc-event', function() {
                var target = $(this);
                $(hoveringEventObj).removeClass('event-hovering');
                target.addClass('event-hovering');
                hoveringEventObj = target;
            });
            $('#calendar').on('mouseleave', '.fc-event', function() {
                var target = $(this);
                $(target).removeClass('event-hovering');
            });
            var selectedEventObj;
            $('#calendar').on('click', '.fc-event, fc-event-inner, fc-event-title', function() {
                window.clearTimeout(event_select_timer);
                var target = $(this);
                $(selectedEventObj).removeClass('event-selected');
                target.addClass('event-selected');
                selectedEventObj = target;
            });
            var event_select_timer;
            $(document.body).mousedown(function(){
                window.clearTimeout(event_select_timer);
                var ecell = $('div[class*="event-selected"]');
                window.setTimeout(function(){                
                    $(ecell).removeClass('event-selected');
                }, 100);            
            });
            function hideTimeline(){
                $('div.rk-timeline').hide();
            }
            function hideTips() {
                if (!g_calendarInstance) return;
                hideEditorTip();
                hideViewerTip();
            };

            function hideEditorTip() {
                removeGhostEvent();
                if (g_editorTipInstance) g_editorTipInstance.hide();
            }

            function hideViewerTip() {
                if (g_popedTipIds.length > 0)
                    while (g_popedTipIds.length) {
                        var id = g_popedTipIds.shift();
                        $('#qtip-' + id).qtip('destroy');
                    }
                g_popedTipIds = [];
            }

            function popupEditorTip(jsEvent, view, info) {
                var viewName = view.name;

                if (!info.act) info.act = 'create';
                var start = moment(info.start);
                var end = moment(info.end);
                //if(viewName == 'month')end.subtract(1, 'days');
                var userId = scheduleUtil.getDisplaySetting('userId');
                var creatorId = currentPageUserId;

                var userInfo = rk_userService.getUserInfo(userId);
                var creatorInfo = rk_userService.getUserInfo(creatorId);

                var userName = userInfo ? userInfo.name : null;
                var creatorName = creatorInfo ? creatorInfo.name : null;

                var option = {
                    id: info.id,
                    act: info.act,
                    viewName: viewName,
                    creatorId: creatorId,
                    creatorName: creatorName,
                    ownerUser: SESSION.user,
                    userId: userId,
                    userName: userName,
                    isAllDay: (info.isAllDay === false ? false : true), //(viewName != 'month' ? !!info.isAllDay : true),
                    startDate: viewName != 'month' ? start.format('YYYY-MM-DD') : start.format('YYYY-MM-DD'),
                    startTime: viewName != 'month' ? start.format('HH:mm:ss') : null,
                    endDate: viewName != 'month' ? end.format('YYYY-MM-DD') : end.format('YYYY-MM-DD'),
                    endTime: viewName != 'month' ? end.format('HH:mm:ss') : null,
                    eventType: null
                };
                scheduleUtil.popupEditor(option);
            };

            function popupViewerTip(jsEvent, view, calEvent) {
                var viewName = view.name;
                //if(viewName != 'month') return;
                removeGhostEvent();
                var config = {
                    events: {
                        render: function(event, api) {}, // Called when tooltip rendered
                        move: function(event, api) {}, // Called when tooltip repositioned
                        show: function(event, api) {},
                        hide: function(event, api) {}, // Called when tooltip is about to be hidden
                        toggle: function(event, api) {}, // Shortcut to binding to two events above
                        visible: function(event, api) {}, // Called when tooltip is shown
                        hidden: function(event, api) {}, // Called when tooltip is hidden
                        focus: function(event, api) {}, // Called when tooltip gains focus
                        blur: function(event, api) {} // Called when tooltip loses focus
                    }
                }
                var target = jsEvent.currentTarget;
                config = $.extend(true, config, commonTipConfig, {
                    position: {
                        target: target
                    }
                });
                var tip = $(target).qtip(config).qtip('show', jsEvent);
                var api = tip.qtip('api');
                var id = api.id;
                g_popedTipIds.push(id);

                var data = {
                    eventId: calEvent.id,
                    startDate: calEvent.valueStartMom ? calEvent.valueStartMom.format('YYYY-MM-DD') : null,
                    startTime: calEvent.valueStartMom ? calEvent.valueStartMom.format('HH:mm:ss') : null,
                    endDate: calEvent.valueEndMom ? calEvent.valueEndMom.format('YYYY-MM-DD') : null,
                    endTime: calEvent.valueEndMom ? calEvent.valueEndMom.format('HH:mm:ss') : null,
                    planFinishDate: calEvent.planFinishDate ? calEvent.planFinishDate.format('YYYY-MM-DD') : null,
                    eventType: calEvent.planFinishDate ? 'task' : 'schedule',
                    act: 'tip',
                    closeMe: function() {
                        hideViewerTip();
                    }
                };

                //var html = template('template_calEventViewer', data);
                api.set({
                    'content.text': '<div data-plugin="eventViewerWindow" style="min-width:388px;min-height:200px;"></div>' //CONTENT
                });
                var win = api.elements.tooltip.find('[data-plugin="eventViewerWindow"]');
                var opt = {
                    tip: tip,
                    tipId: api.id
                }
                opt = $.extend({}, opt, data);
                win.eventViewerWindow(opt);
                initTipClosing(target, win.eventViewerWindow, api.elements.tooltip);


                window.setTimeout(function() {
                    var oh = $('.fc-event:first').outerHeight();
                    var tooltip = api.elements.tooltip;
                    var top = tooltip.offset().top;
                    var left = tooltip.offset().left;

                    top = top + oh * 1.5;
                    tooltip.animate({
                        'top': top + 'px'
                    }, 50);
                }, 10);

            };


            var tip_close_timer;
            var tip_close_inited;

            function initTipClosing(target, tipWin, tipObj) {
                tipObj.bind('mousemove', function() {
                    window.clearTimeout(tip_close_timer);
                });
                tipObj.bind('mouseup', function() {
                    window.clearTimeout(tip_close_timer);
                });
                if (tip_close_inited) {
                    return;
                }
                var id = $(target).attr('id');
                $(document.body).bind('mousedown', function() {
                    tip_close_timer = window.setTimeout(function() {
                        hideViewerTip();
                    }, 150);
                });
                $('#calendar').on('mouseup', '.fc-event', function(e) {
                    window.clearTimeout(tip_close_timer);
                });
                tip_close_inited = true;
            };
        };


        function initCalendarHeader() {
            var leftCon = g_calendarInstance.find('.fc-header-left');
            var rightCon = g_calendarInstance.find('.fc-header-right');
            var viewName = g_calendarInstance.fullCalendar('getView').name;


            rightCon.css({
                'position': 'relative',
                'text-align': 'left'
            }).html(
                //'<a href="unchecked.action" class="btn-unconfirm">未确认日程(0)</a> <span class="btn-unconfirm-split">|</span> ' +
                //'<a href="javascript:void(0)" class="btn-now">本月</a> | ' +
                '<a class="btn-filter" href="javascript:void(0)">' + rk.i18n('SCHEDULE_SELECT') + '</a> | ' +
                '<a href="javascript:void(0)" class="btn-now">' + rk.i18n('SCHEDULE_THIS_MONTH') + '</a>'
            );
            rightCon.find('.btn-now').click(function() {
                g_calendarInstance.fullCalendar('today');
                $('#oa_panel').schedulePanelCtrl('gotoToday');
            });
            rightCon.find('.btn-filter').calEventFilterCtrl({});

            // var html = require('oa/tmpl/schedule/page/ownerSelector.tpl');
            // leftCon.html(html);
            // //v3.0不在此初始化了
            // $('#ownerSelector').calOwnerSelCtrl({
            //     userId: ''
            // });

            updateBtnNow(viewName);
        };

        function initCreateButton() {
            $('.task_new_area_inlist').click(function() {
                var start = moment();
                start.set('minutes', 0);
                start.set('second', 0);
                start.add(60, 'minutes');
                var end = moment(+start.toDate() + 30 * 60 * 1000)

                var opt = {
                    startDate: start.format('YYYY-MM-DD'),
                    startTime: start.format('HH:mm:ss'),
                    endDate: end.format('YYYY-MM-DD'),
                    endTime: end.format('HH:mm:ss'),
                    viewName: g_calendarInstance.fullCalendar('getView').name,
                    isAllDay: false,
                    act: 'create'
                };
                scheduleUtil.popupEditor(opt);
            });
        };
        function updateBtnNow(viewName){
            switch (viewName) {
                case 'month':
                    g_calendarInstance.find('.btn-now').html(rk.i18n('SCHEDULE_THIS_MONTH'));
                    break;
                case 'agendaWeek':
                    updateWeekTitle_by_asking();
                    g_calendarInstance.find('.btn-now').html(rk.i18n('SCHEDULE_THIS_WEEK'));
                    break;
                case 'agendaDay':
                    updateDayTitle_by_asking();
                    g_calendarInstance.find('.btn-now').html(rk.i18n('SCHEDULE_TODAY'));
                    break;
                default: //
            }
        }

        var commonTipConfig = {
            content: {
                text: ' ',
                title: {
                    button: false
                }
            },
            position: {
                my: 'bottom left',
                at: 'top left',
                adjust: {
                    mouse: false,
                    x: 0,
                    y: 0,
                    scroll: false,
                    resize: true
                }
            },
            show: {
                event: 'click',
                solo: true
            },
            hide: {
                event: null //
            },
            style: {
                classes: 'qtip-shadow qtip-light'
            }
        };

    })();

    return calendarPage;
});